package com.application.validate;

import com.application.model.Category;
import com.application.module.recommend.Recommend;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

import java.util.List;

public class CategoryValidator extends ApiValidator {
    @Override
    protected void validate(Controller c) {
        String key = getActionKey();
        if ("/admin/category/update".equalsIgnoreCase(key)) {
            //判断上级分类是否合法
            String cid = c.getPara();
            Integer pid = c.getParaToInt("parent_id");
            Category cat = Category.dao.findById(cid);
            if(cat.getId() == pid){
                addError("msg", "请选择正确的上级分类");
                return;
            }

            Integer status = c.getParaToInt("category_status");
            //禁用时,如有子级数据,需全部禁用
            if(status != null && status == 0){
                List<Category> list = Category.dao.findListByParentId(Integer.valueOf(cid));
                if(list.size() > 0){
                    addError("msg", "请先停用所有的子级分类");
                    return;
                }
            }
        } else if("/admin/category/updateOrd".equalsIgnoreCase(key)){
            validateInteger("category_ord", "msg", "请输入整数");
        } else if("/admin/category/save".equalsIgnoreCase(key)){
            validateRequired("category_status", "msg", "状态项必选");
        } else if("/adminapi/category/delete".equalsIgnoreCase(key)) {
            valiDel(c);
        }

    }

    private void valiDel(Controller c) {
        String str = c.getPara("id");
        for (String s : str.split(",")) {
            if(StrKit.notBlank(s)) {
                //首页推荐是否存在
                Recommend obj = Recommend.dao.findByModuleId(Recommend.TYPE_CAT, Integer.parseInt(s));
                if(obj != null) {
                    addError("请先删除首页推荐中内容");
                }
            }
        }
    }
}
